package com.grant.code.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component  // 添加组件注解
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;  // Spring会自动调用此方法注入上下文
    }

    // 防止工具类被实例化
    private SpringContextUtils() {}

    public static <T> T getBean(Class<T> beanClass) {
        if (context == null) {
            throw new IllegalStateException("ApplicationContext未初始化!");
        }
        return context.getBean(beanClass);
    }
}
